package com.yin.myproject.zk.client;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.List;
import java.util.ResourceBundle;

/**
 * Created by Eason on 2017/8/4.
 */
public class ZkClient {

    private static CuratorFramework client;

    /**
     * 静态块:实例化一个Zookeeper客户端
     */
    static {
        ResourceBundle bundle = ResourceBundle.getBundle("zk");
        String connectString = bundle.getString("zk");
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.newClient(connectString, retryPolicy);
    }

    /**
     * 获取一个新的ZK会话客户端
     *
     * @return
     */
    public static CuratorFramework getNewZkClient() {
        ResourceBundle bundle = ResourceBundle.getBundle("zk");
        String connectString = bundle.getString("zk");
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);
        return CuratorFrameworkFactory.newClient(connectString, retryPolicy);
    }

    /**
     * 获取ZK会话客户端
     *
     * @return
     */
    public static CuratorFramework getZkClient() {
        return client;
    }


    public static void main(String[] args) throws Exception {
        CuratorFramework zkClient = getZkClient();
        zkClient.start();
        List<String> strings = zkClient.getChildren().forPath("/task/node");
        for (String string : strings) {
            System.out.println(string);
            zkClient.delete().forPath("/task/node/"+string);
        }
    }
}
